﻿using System;
using System.Collections.Generic;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace MBA.FluentExt.Ext
{
	public abstract class ExtObject
	{
		#region Fields

		internal SortedDictionary<string, object> configDictionary = new SortedDictionary<string, object>();

		#endregion Fields

		#region Methods

		protected abstract string ExtNamespace { get; }

		public virtual string ToConstructor()
		{
			return "new {0}({1})".FormatWith(ExtNamespace, ToString());
		}

		public string GetId()
		{
			object idValue;

			if (configDictionary.TryGetValue("id", out idValue) == false)
			{
				return null;
			}	

			return idValue.ToString();
		}

		public string ToJavascriptVar(string varName = null)
		{
			if (varName == null)
			{
				varName = GetId();

				if (varName == null)
				{
					throw new ArgumentNullException("varName",
																					"The varName argument can be ommited only if this component has an id set");
				}
			}

			return "var {0}={1};".FormatWith(varName, ToConstructor());
		}

		public override string ToString()
		{
#if DEBUG
			const Formatting format = Formatting.Indented;
#else
			const Formatting format = Formatting.None;
#endif

			return JsonConvert.SerializeObject(configDictionary, format, new JavaScriptDateTimeConverter());
		}

		protected T Config<T>(string key, object value)
			where T : ExtObject
		{
			configDictionary[key] = value;

			return this as T;
		}

		#endregion Methods
	}
}